import java.util.NoSuchElementException;

public class ProcessCircleList {
	protected ProcessNode head;  //Current head
	protected ProcessNode tail; //tail
	protected int size; //list size
	
	//Create new process list
	public ProcessCircleList()
	{
		head = null;
		size = 0;
	}
	
	//Get list size
	public int size()
	{
		return size;
	}
	
	//Get head
	public ProcessNode getHead()
	{
		return head;
	}
	
	//Move head forward
	public void advance()
	{
		head = head.getNext();
	}
	
	public void add(ProcessNode newProcessNode) {
		if (head == null) {
		   size++;
		   head = newProcessNode;
		   head.setNext(head);
		   tail = head;
		   return;
		 }
		  size++;
		  newProcessNode.setNext(head);
		  head = newProcessNode;
		  tail.setNext(head);
	}
	
	//Remove node after head
	public ProcessNode remove()
	{
		ProcessNode oldProcessNode = head.getNext();
		if(oldProcessNode == head)
		{
			head = null;
		}
		else
		{
			head.setNext(oldProcessNode.getNext());
			oldProcessNode.setNext(null);
		}		
		size--;
		return oldProcessNode;
	}
	
	/**
	 * Remove ProcessNode based on an ID.
	 * @param processId
	 * @return
	 */
	public int remove(int processId) {
		
		  if (head == null || tail == null)
		   throw new NoSuchElementException();
		  
		  ProcessNode current = head, temp = head, found = null;
		  if (processId == head.getProcess().getProcessId()) {
		   if (head.getNext() == head) {
		    found = head;
		    head = null;
		    tail = null;
		    size--;
		    return found.getProcess().getProcessId();
		   } else {
		    found = head;
		    temp = tail;
		   }
		  } else {
		   current = head.getNext();
		   while (current != head) {
		    if (current.getProcess().getProcessId() == processId) {
		     found = current;
		     break;
		    }
		    temp = current;
		    current = current.getNext();
		   }
		  }
		  if (found == null) {
		   throw new NoSuchElementException("Process: " + processId);
		  }
		  
		  int result = found.getProcess().getProcessId();
		  temp.setNext(found.getNext());
		  found.setNext(null);
		  found.setProcess(null);
		  size--;
		  return result;
		 
	}
	
	
//	public String toString()
//	{
//		ProcessNode current = head;
//		if(head == null)
//		{
//			return "[]";
//		}
//		
//		current = head.getNext();
//		String listString = "[" + head.getProcess().getProcessId();
//		while (current != head) 
//		{
//			listString += ", " + current.getProcess().getProcessId();   
//		}	
//	
//		
//		return listString + "]";
//	}
	
	
}
